package com.edgclub.edg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.param.MessageParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.model.result.RunData;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.UserBeanDao;
import com.hyphenate.easeui.model.ChatBean;
import com.hyphenate.easeui.model.UserBean;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 支付管理
 */
public class ChatSettingActivity extends GzBaseTooolBarActivity implements
        OnClickListener ,VolleyListener{

    private EditText mBzm;
    private CheckBox mMess_ltsz;
    private CheckBox mMess_mdr;
    private TextView mPinbi_btn;
    private TextView mLock_btn;
    private TextView mClear_btn;
    private TextView mOutgroup_btn;
    private LinearLayout bz_layout;

    protected String toChatUsername;
    public ChatBean chatBean;
    private int chatType;
    private EMGroup group;
    private List<String>topList;
    private List<String>blacklist;
    private List<String>disturbList;
    private UserBean bean;

    private RelativeLayout group_number;

    @Override
    public int getContentView() {
        return R.layout.activity_chatsetting;
    }
    @Override
    public void setTitleBarView() {
        setCustomActionBar();
        title.setText("聊天设置");
        main_back.setOnClickListener(this);
    }
    @Override
    public void initView() {
        group_number = (RelativeLayout) findViewById(R.id.group_number);
        group_number.setOnClickListener(this);
        topList= (List<String>) SerializeManager.loadFile(Constant.placeTotop+ GuZhiApplication.getInstance().getUserId()+"");
        disturbList= (List<String>) SerializeManager.loadFile(Constant.notDisturb+ GuZhiApplication.getInstance().getUserId()+"");
        if(null==topList)
            topList=new ArrayList<>();
        if(null==disturbList)
            disturbList=new ArrayList<>();
        try {
            blacklist=EMClient.getInstance().contactManager().getBlackListUsernames();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(null==blacklist) blacklist=new ArrayList<>();
        bz_layout= (LinearLayout) findViewById(R.id.bz_layout);
        mBzm = (EditText) findViewById(R.id.bzm);
        mMess_ltsz = (CheckBox) findViewById(R.id.mess_ltsz);
        mMess_mdr = (CheckBox) findViewById(R.id.mess_mdr);
        mPinbi_btn = (TextView) findViewById(R.id.pinbi_btn);
        mLock_btn = (TextView) findViewById(R.id.lock_btn);
        mClear_btn = (TextView) findViewById(R.id.clear_btn);
        mOutgroup_btn= (TextView) findViewById(R.id.outgroup_btn);
        chatBean= (ChatBean) getIntent().getSerializableExtra("chatBean");
        if(blacklist.contains(chatBean.getImid())){
            mPinbi_btn.setText("解除屏蔽");
        }
        chatType=chatBean.getChatType();
        if(chatType!=1){
//            group = EMClient.getInstance().groupManager().getGroup(chatBean.getImid());
//            if(group.isMsgBlocked()){
//                mMess_mdr.setChecked(true);
//            }else{
//                mMess_mdr.setChecked(false);
//            }
            bz_layout.setVisibility(View.GONE);
            mPinbi_btn.setVisibility(View.GONE);
            mLock_btn.setVisibility(View.GONE);
            mOutgroup_btn.setVisibility(View.VISIBLE);
            group_number.setVisibility(View.VISIBLE);
        }else{
            bean= (UserBean) DaoHelper.getInstance(this, EaseConstant.DB_NAME_CHAT).getTypeId(UserBeanDao.Properties.Imid,chatBean.getImid());
            if(null!=bean){
                if(!"".equals(bean.getUsername()))
                    mBzm.setText(bean.getUsername());
                else
                    mBzm.setText(bean.getNick());
            }
//            right_layout.setVisibility(View.VISIBLE);
//            right_text.setText("完成");
//            right_layout.setOnClickListener(this);
            mPinbi_btn.setVisibility(View.VISIBLE);
            mPinbi_btn.setOnClickListener(this);
            mLock_btn.setVisibility(View.VISIBLE);
            mOutgroup_btn.setVisibility(View.GONE);
            group_number.setVisibility(View.GONE);
        }

        mBzm.setSelection(mBzm.getText().length());
        mOutgroup_btn.setOnClickListener(this);
        mClear_btn.setOnClickListener(this);
        mLock_btn.setOnClickListener(this);
        if(disturbList.contains(chatBean.getImid())){
            mMess_mdr.setChecked(true);
        }else{
            mMess_mdr.setChecked(false);
        }
        if(null!=topList&&topList.contains(chatBean.getImid())){
            mMess_ltsz.setChecked(true);
        }else{
            mMess_ltsz.setChecked(false);
        }
        mMess_ltsz.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    if(!topList.contains(chatBean.getImid())){
                        topList.add(chatBean.getImid());
                    }
                }else{
                    topList.remove(chatBean.getImid());
                }
                SerializeManager.saveFile(topList,Constant.placeTotop+ GuZhiApplication.getInstance().getUserId()+"");
            }
        });

        mMess_mdr.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    if(!disturbList.contains(chatBean.getImid())){
                        disturbList.add(chatBean.getImid());
                    }
                }else{
                    disturbList.remove(chatBean.getImid());
                }
                SerializeManager.saveFile(disturbList,Constant.notDisturb+ GuZhiApplication.getInstance().getUserId()+"");
                DemoHelper.getInstance().setDisturbList(disturbList);
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.CHATLIST_DISTURB);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
//                toggleBlockGroup(b,chatBean);
            }
        });
    }
    @Override
    public void initData() {
        toChatUsername=chatBean.getImid();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_layout:
//                if("".equals(mBzm.getText()+"".trim())){
//                    Toast.makeText(this,"备注名不可为空！",Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                MessageParam messageParam=new MessageParam();
//                messageParam.setToUserId(chatBean.getId());
//                messageParam.setUserId(new UserPrefUtils(this).getUser().getId() + "");
//                messageParam.setAlias(mBzm.getText()+"");
//                new FriendApi(this).AddAlias(messageParam,this);
                break;
            case R.id.pinbi_btn:
                if("屏蔽Ta私信".equals(mPinbi_btn.getText()+"")){
                    toggleBlockGroup(true,chatBean);
                }else{
                    toggleBlockGroup(false,chatBean);
                }

                break;
            case R.id.clear_btn:
                emptyHistory();
                break;
            case R.id.lock_btn:
                Intent intent1=new Intent(this,ChatBlacklistActivity.class);
                startActivity(intent1);
                break;
            case R.id.main_back:
                if(1==chatBean.getChatType()){
                    if(bean!=null && (bean.getNick().equals(mBzm.getText().toString().trim()) || bean.getAlias().equals(mBzm.getText().toString().trim()))){
                        Intent intent=new Intent();
                        setResult(RESULT_OK, intent);
                        finish();
                    }else{
                        MessageParam messageParam=new MessageParam();
                        messageParam.setToUserId(chatBean.getId());
                        messageParam.setUserId(new UserPrefUtils(this).getUser().getId() + "");
                        messageParam.setAlias(mBzm.getText()+"");
                        new FriendApi(this).AddAlias(messageParam,this);
                    }

                }else{
                    Intent intent=new Intent();
                    setResult(RESULT_OK, intent);
                    finish();

                }

                break;
            case R.id.outgroup_btn:
                addGroup(false);
                break;
            case R.id.group_number:
                Intent intent=new Intent(this, GroupMembersActivity.class);
                intent.putExtra("groupid",chatBean.getGroupid());
                startActivity(intent);
                break;
            default:
                break;
        }
    }
    /**
     * 加入或退出群组
     */
    private void addGroup(boolean res){
        MessageParam messageParam=new MessageParam();
        messageParam.setGroupid(chatBean.getGroupid());
        messageParam.setUserId(new UserPrefUtils(this).getUser().getId() + "");
        if(res)
            new FriendApi(this).AddGroupQuit(messageParam,this);
        else
            new FriendApi(this).quitGroup(messageParam,this);

    }

    private void toggleBlockGroup(boolean res,final ChatBean chatBean1) {
        if(!res){
            showDialog(getResources().getString(R.string.Is_unblock),false);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        if(chatBean1.getChatType()==Constant.CHATTYPE_GROUP)
                             EMClient.getInstance().groupManager().unblockGroupMessage(chatBean1.getImid());
                        else {
                            EMClient.getInstance().contactManager().removeUserFromBlackList(chatBean1.getImid());
                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                mPinbi_btn.setText("屏蔽Ta私信");
                                dismissDialog();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                dismissDialog();
                                Toast.makeText(getApplicationContext(),"解除屏蔽失败", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                }
            }).start();

        } else {
            showDialog("正在屏蔽Ta的私信",false);
            final String st9 = getResources().getString(R.string.group_of_shielding);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        if(chatBean1.getChatType()==Constant.CHATTYPE_GROUP)
                             EMClient.getInstance().groupManager().blockGroupMessage(chatBean1.getImid());
                        else {
                            EMClient.getInstance().contactManager().addUserToBlackList(chatBean1.getImid(), true);

                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                dismissDialog();
                                mPinbi_btn.setText("解除屏蔽");
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                dismissDialog();
                                Toast.makeText(getApplicationContext(), st9, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }
            }).start();
        }
    }
    /**
     * 点击清空聊天记录
     *
     */
    protected void emptyHistory() {
        String msg = getResources().getString(com.hyphenate.easeui.R.string.Whether_to_empty_all_chats);
        new EaseAlertDialog(this,null, msg, null,new EaseAlertDialog.AlertDialogUser() {

            @Override
            public void onResult(boolean confirmed, Bundle bundle) {
                if(confirmed){
                    // 清空会话
                    EMClient.getInstance().chatManager().deleteConversation(toChatUsername, true);
                }
            }
        }, true).show();
    }
    @Override
    public void onStart(String tag) {
        showDialog("正在请求...",false);
    }

    @Override
    public void onSuccess(String response, String tag) {
        dismissDialog();
        if (JSONHelper.isSuccess(response)) {
            RunData data = JsonUtil.getMode(response,
                    RunData.class);
            if(tag.equals(ApiConfig.APIURL.URL_ALIAS)){
                if ("操作成功".equals(data.getData())) {
                    if(null!=bean)
                        bean.setUsername(mBzm.getText()+"");
                    HashMap<String, Object> hashMap = new HashMap<String, Object>();
                    hashMap.put("event", BroadCastEvent.CHATTITLE_REFRESH);
                    hashMap.put("imid", bean.getImid());
                    EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                            ThreadEnforcer.MAIN).post(hashMap);
                    DaoHelper.getInstance(this, EaseConstant.DB_NAME_CHAT).update(bean);
                    StringUtils.postToast(ChatSettingActivity.this, data.getData() + "");
                    finish();
                } else {
                    StringUtils.postToast(ChatSettingActivity.this, data.getData() + "");
                }
            }else {
                if ("退群成功".equals(data.getData())) {
                    StringUtils.postToast(ChatSettingActivity.this, data.getData() + "");
                    HashMap<String, Object> hashMap = new HashMap<String, Object>();
                    hashMap.put("event", BroadCastEvent.BB_GROUP_REFUL);
                    hashMap.put("obj",true);
                    EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                            ThreadEnforcer.MAIN).post(hashMap);
                    finish();
                } else {
                    StringUtils.postToast(ChatSettingActivity.this, data.getData() + "");
                }
            }
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        dismissDialog();
        ResultCode.toastVolleyError(this, volleyError);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            onClick(main_back);
//            Intent intent=new Intent();
//            setResult(RESULT_OK, intent);
//            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
